package com.jxm.spring.security.security.handler;

import com.alibaba.fastjson.JSON;
import com.jxm.spring.security.common.ResponseUtils;
import com.jxm.spring.security.security.domain.SysUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2021/5/16 18:41
 * @Version: 1.0
 */
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        SysUserDetails sysUserDetails = (SysUserDetails) authentication.getPrincipal();
        //创建token
//        String token = JWTTokenUtil.createAccessToken(sysUserDetails);

        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("user:"+token,JSON.toJSONString(sysUserDetails));

        ResponseUtils.responseJson(response, ResponseUtils.response(200, "登录成功", token));
    }
}
